<?php

namespace app\sys\controller;

use think\Db;

// 后台 订单记录管理
class Order extends Admin
{
    public function index()
    {
        $admin_info = session('admin_info');
        $date = input('param.date', '');
        $status = input('param.status', '');
        $express = input('param.express', '');
        $page = input('param.page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = input('param.limit', 20);
        $order_field = input('param.field', '');
        $order_type = input('param.order', 0);
        $query = [];
        $status = explode(',', $status);
        foreach ($status as $key => $value) {
            $status[$key] = intval($value);
        }
        // 供应商只能看到自己的
        if (6 == $admin_info['permission']) {
            $query['admin_id'] = $admin_info['id'];
        }
        if (request()->isAjax()) {
            if ([''] != $status && ['-1'] != $status) {
                $query['status'] = ['in', $status];
            }
            if ($date) {
                $arr = explode('~', $date);
                $query['ct'] = [['gte', strtotime(trim($arr[0]))], ['lte', strtotime(trim($arr[1]).'23:59:59')]];
            }

            if ('顺丰' == $express) {
                $query['express'] = $express;
            }
            if ('普通快递' == $express) {
                $query['express'] = ['neq', '顺丰'];
            }
            $order = ['ct' => -1];
            if ($order_field && $order_type) {
                $order[$order_field] = 'asc' == $order_type ? 1 : -1;
            }
            $status_list = config('order_status');
            $list = Db::name('order')->where($query)->page($page)->limit($limit)->order($order)->select();
            foreach ($list as $key => $value) {
                foreach ($value['address'] as $k => $v) {
                    $a = Db::name('address')->find($v['address_id']);
                    $value['address'][$k] = ['consignee' => $a['consignee'], 'number' => $v['number'], 'phone' => $a['phone'], 'address' => $a['address'], 'express_code' => $v['express_code'], 'express_number' => $v['express_number']];
                }
                $list[$key]['address'] = $value['address'];
                foreach ($value['product'] as $k => $v) {
                    $q = ['id' => $v['product_id']];
                    if (6 == $admin_info['permission']) {
                        $q['admin_id'] = $admin_info['id'];
                    }
                    $p = Db::name('product')->where($q)->field('name')->find();
                    if ($p) {
                        $value['product'][$k] = ['name' => strval($p['name']), 'specifications' => $v['specifications'], 'number' => $v['number'], 'price' => $v['price'], 'postage' => $v['postage']];
                    }
                }
                $list[$key]['product'] = $value['product'];
                foreach ($value['red_packet'] as $kk => $vv) {
                    $list[$key]['red_packet'][$kk]['type'] = $vv['type'];
                    $list[$key]['red_packet'][$kk]['user_name'] = strval(Db::name('user')->find($vv['user_id'])['name']);
                }

                // $gang_info = Db::name('gang')->find($value['gang_id']);
                // $buyer_info = Db::name('user')->find($value['buyer']);
                // $seller_info = Db::name('user')->find($value['seller']);
                // $inviter_info = Db::name('user')->find($value['inviter_id']);
                $list[$key]['status'] = $status_list[$value['status']];
                // $list[$key]['gang_name'] = strval($gang_info['name']);
                // $list[$key]['buyer_name'] = strval($buyer_info['name']);
                // $list[$key]['seller_name'] = strval($seller_info['name']);
                // $list[$key]['inviter_name'] = strval($inviter_info['name']);
                $list[$key]['pay_time'] = date('Y-m-d H:i:s', $value['pay_time']);
                $list[$key]['ct'] = date('Y-m-d H:i:s', $value['ct']);
            }
            $count = Db::name('order')->where($query)->count();

            return success(['data' => $list, 'count' => $count]);
        }

        unset($query['status']);
        $count['count_all'] = Db::name('order')->where($query)->count();
        $query['status'] = 1;
        $count['count_0'] = Db::name('order')->where($query)->count();
        $query['status'] = 2;
        $count['count_1'] = Db::name('order')->where($query)->count();
        $query['status'] = 10;
        $count['count_2'] = Db::name('order')->where($query)->count();
        $query['status'] = ['in', [5, 7, 8, 11]];
        $count['count_3'] = Db::name('order')->where($query)->count();
        $query['status'] = ['in', [4, 6, 13, 14, 15]];
        $count['count_4'] = Db::name('order')->where($query)->count();

        return view('index', ['count' => $count]);
    }

    // 发货接口（如果未发货状态客户申请退款 [此时供应商线下已经发货了但未录入系统] 则还是将状态改为已发货）
    public function sendGoods()
    {
        $order_id = input('param.id', '');
        $order_info = Db::name('order')->where(['id' => $order_id])->find();
        $express_list = Db::name('express')->select();
        if (request()->isPost()) {
            $admin_info = session('admin_info');
            if ($admin_info['permission'] < 6) {
                return error('你的权限不够');
            }
            if (!$order_id || 24 != strlen($order_id)) {
                return error('参数错误：错误的order_id');
            }
            if (1 != $order_info['status']) {
                return error('该订单不是待发货状态');
            }
            $address = input('post.address/a', []);
            foreach ($order_info['address'] as $key => $value) {
                if (!$address[$key]['code']) {
                    return error('请选择第'.($key + 1).'个地址的物流公司');
                }
                if (!$address[$key]['number']) {
                    return error('请选择第'.($key + 1).'个地址的运单号');
                }

                $value['express_code'] = $address[$key]['code'];
                $value['express_number'] = $address[$key]['number'];
                $order_info['address'][$key] = $value;
            }
            Db::name('order')->where('id', $order_id)->update(['status' => 2, 'send_time' => time(), 'address' => $order_info['address'], 'send_admin_id' => $admin_info['id']]);

            $product = Db::name('product')->field('name')->find($order_info['product'][0]['product_id']);
            $user_info = Db::name('user')->find($order_info['buyer']);
            $order_express = ['name' => '', 'number' => ''];
            foreach ($express_list as $k => $v) {
                if ($order_info['address'][0]['express_code'] == $v['code']) {
                    $order_express['name'] = $v['name'];
                    $a = Db::name('address')->find($v['address_id']);
                    $order_express['number'] = $order_info['address'][0]['express_number'];
                    $order_express['consignee'] = $a['consignee'];
                    $order_express['phone'] = $a['phone'];
                    $order_express['address'] = $a['address'];
                    break;
                }
            }
            if ($user_info['gzh_openid']) {
                //  发送公众号模板消息
                $wxgzh_service = new \wx\WxgzhService();
                $data = [
                    'first' => ['value' => '您的订单已发货！'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval($order_info['product'][0]['number'])],
                    'keyword4' => ['value' => strval($order_info['total_money'].'元')],
                    'remark' => ['value' => '商品已发出请注意查收', 'color' => '#173177'],
                ];
                $wxgzh_service->sendTemplateMsg($user_info['gzh_openid'], 'LTtfunnRUl9VZWqrXQ_LCt2UJhblh8v0-9sJSaSGKrU', $data, 'pages/index/welcome');
            } elseif ($order_info['prepay_id']) {
                $wx_service = new \wx\WeixinService();
                $tData = [
                        'keyword1' => ['value' => strval($order_info['id'])],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => strval($order_info['total_money']).'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                        'keyword5' => ['value' => strval($order_express['number'])],
                        'keyword6' => ['value' => strval($order_express['name'])],
                        'keyword7' => ['value' => strval($order_express['consignee'])],
                        'keyword8' => ['value' => strval($order_express['address'])],
                        'keyword9' => ['value' => strval($order_express['phone'])],
                    ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'FOdLYGllplk8H09A4ipfHCFaQR5QMZ7_lC4Tg7uCTak', 'pages/index/welcome', $tData);
            }

            return success();
        }
        foreach ($order_info['address'] as $k => $v) {
            $a = Db::name('address')->find($v['address_id']);
            $order_info['address'][$k] = ['consignee' => $a['consignee'], 'number' => $v['number'], 'phone' => $a['phone'], 'address' => $a['address'], 'express_code' => $v['express_code'], 'express_number' => $v['express_number']];
        }

        return view('sendGoods', ['express_list' => $express_list, 'info' => $order_info]);
    }

    // 详情页
    public function orderInfo()
    {
        $order_id = input('param.id', '');
        $order_info = Db::name('order')->find($order_id);
        foreach ($order_info['address'] as $k => $v) {
            $a = Db::name('address')->find($v['address_id']);
            $order_info['address'][$k] = ['consignee' => $a['consignee'], 'number' => $v['number'], 'phone' => $a['phone'], 'address' => $a['address'], 'express_code' => $v['express_code'], 'express_number' => $v['express_number']];
        }
        foreach ($order_info['product'] as $k => $v) {
            $q = ['id' => $v['product_id']];
            if (6 == $admin_info['permission']) {
                $q['admin_id'] = $admin_info['id'];
            }
            $p = Db::name('product')->where($q)->field('name')->find();
            if ($p) {
                $order_info['product'][$k] = ['name' => strval($p['name']), 'specifications' => $v['specifications'], 'number' => $v['number'], 'price' => $v['price'], 'postage' => $v['postage']];
            }
        }
        foreach ($order_info['red_packet'] as $kk => $vv) {
            $order_info['red_packet'][$kk]['type'] = $vv['type'];
            $order_info['red_packet'][$kk]['user_name'] = strval(Db::name('user')->find($vv['user_id'])['name']);
        }

        $order_info['status'] = config('order_status')[$order_info['status']];
        $order_info['ct'] = date('Y-m-d H:i:s', $order_info['ct']);
        if ($order_info['pay_time']) {
            $order_info['pay_time'] = date('Y-m-d H:i:s', $order_info['pay_time']);
        }
        if ($order_info['apply_time']) {
            $order_info['apply_time'] = date('Y-m-d H:i:s', $order_info['apply_time']);
        }
        if ($order_info['send_time']) {
            $order_info['send_time'] = date('Y-m-d H:i:s', $order_info['send_time']);
        }
        if ($order_info['confirm_refund_time']) {
            $order_info['confirm_refund_time'] = date('Y-m-d H:i:s', $order_info['confirm_refund_time']);
        }
        if ($order_info['refund_time']) {
            $order_info['refund_time'] = date('Y-m-d H:i:s', $order_info['refund_time']);
        }
        if ($order_info['reject_refund_time']) {
            $order_info['reject_refund_time'] = date('Y-m-d H:i:s', $order_info['reject_refund_time']);
        }
        if ($order_info['confirm_return_goods_time']) {
            $order_info['confirm_return_goods_time'] = date('Y-m-d H:i:s', $order_info['confirm_return_goods_time']);
        }
        if ($order_info['buyer_send_time']) {
            $order_info['buyer_send_time'] = date('Y-m-d H:i:s', $order_info['buyer_send_time']);
        }
        if ($order_info['seller_receive_time']) {
            $order_info['seller_receive_time'] = date('Y-m-d H:i:s', $order_info['seller_receive_time']);
        }
        if ($order_info['receive_time']) {
            $order_info['receive_time'] = date('Y-m-d H:i:s', $order_info['receive_time']);
        }

        $express_list = Db::name('express')->select();
        foreach ($order_info['address'] as $key => $value) {
            foreach ($express_list as $v) {
                if ($v['code'] == $value['express_code']) {
                    $order_info['address'][$key]['express_name'] = $v['name'];
                }
            }
        }
        if ($order_info['buyer_send_code']) {
            foreach ($express_list as $v) {
                if ($v['code'] == $order_info['buyer_send_code']) {
                    $order_info['buyer_send_name'] = $v['name'];
                }
            }
        }
        // dump($order_info);
        return view('orderInfo', $order_info);
    }

    // 确认退款、同意退货  (供应商)
    public function confirmRefund()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $order_info = Db::name('order')->where(['id' => $order_id])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (5 != $order_info['status'] && 6 != $order_info['status']) {
            return error('该订单不是申请退款状态，不能确认退款');
        }
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        $product = Db::name('product')->find($order_info['product'][0]['product_id']);
        if (isset($order_info['send_time'])) {
            // 同意退货
            // 1发货了 先同意退款 然后买家发货 卖家收货后 退款减去运费
            $return_money = round($order_info['apply_refund_money'] - $order_info['total_postage'], 2);
            Db::name('order')->where('id', $order_id)->update(['status' => 13, 'confirm_return_goods_time' => time()]);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 同意退货（给买家）
                $data = [
                    'first' => ['value' => '您申请退货的订单，卖家已经同意退货'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval(intval($order_info['total_number']))],
                    'keyword4' => ['value' => strval($order_info['total_money']).'元'],
                    'remark' => ['value' => '请买家在7天内发货给卖家'],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'YT1kCxUnMDp91qWS21jYqsi_XZFNUA9CQirveh9NL1A', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                // 发送模板消息
                $tData = [
                'keyword1' => ['value' => $order_id],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => $return_money.'元'],
                'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                'keyword5' => ['value' => '同意退货'],
                'keyword6' => ['value' => '请买家在7天内发货给卖家'],
            ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
            }
        } else {
            // 确认退款
            // 2支付完未发货(支付时间后10天内才可以操作)，直接退全款
            Db::name('order')->where('id', $order_id)->update(['status' => 7, 'confirm_refund_time' => time()]);
            // 减少待结算金额
            notSettlemetnChange($order_info, false);
            $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], round($order_info['total_fee'], 2), round($order_info['apply_refund_money'], 2));
            if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
                Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 11, 'refund_time' => time()]);
                $db_ui = Db::name('user')->find($order_info['buyer']);
                if ($db_ui['gzh_openid']) {
                    //发送模板消息 公众号 退款成功（给买家）
                    $data = [
                        'first' => ['value' => '您申请的退款已通过'],
                        'keyword1' => ['value' => strval($order_info['total_fee']).'元'],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => strval($order_info['id'])],
                        'keyword4' => ['value' => strval($order_info['reason'])],
                        'remark' => ['value' => '已退回微信零钱，感谢使用。'],
                    ];
                    $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'RlLrUWzjsVqcRd5DxTDhZ1mti7m97ZFxtKgsNUX_bNI', $data, 'pages/index/welcome');
                } elseif ($order_info['openid']) {
                    // 发送模板消息
                    $tData = [
                        'keyword1' => ['value' => $order_id],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => $order_info['apply_refund_money'].'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                        'keyword5' => ['value' => '已退回微信零钱'],
                    ];
                    $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], '6hSfXpoutPciTAJYli9XI05Lqzg9wH7n4GjlD2oV5E8', 'pages/index/welcome', $tData);
                }

                return success('自动退款成功');
            }

            return error('微信支付返回：'.$result['return_msg']);
        }

        return success('自动退款失败');
    }

    // 拒绝退货(供应商) 没有拒绝退款 付款后供应商只能同意退款或者发货
    public function rejectRefund()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $reason = input('post.reason', '');
        if (!$reason) {
            return error('请填写理由');
        }
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $order_info = Db::name('order')->where(['id' => $order_id])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (5 != $order_info['status'] && 6 != $order_info['status']) {
            return error('该订单不是申请退款状态，不能拒绝退款');
        }
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        $product = Db::name('product')->find($order_info['product'][0]['product_id']);
        //该订单申请退款已超过3天（没发货），将自动同意退款，但自动退款失败！
        if (isset($order_info['apply_time']) && !$order_info['send_time'] && $order_info['apply_time'] < time() - 86400 * 3) {
            Db::name('order')->where('id', $order_id)->update(['status' => 7, 'confirm_refund_time' => time()]);
            $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], round($order_info['total_fee'], 2), round($order_info['apply_refund_money'], 2));
            if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
                Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 11, 'refund_time' => time()]);
                // 减少待结算金额
                notSettlemetnChange($order_info, false);
                $db_ui = Db::name('user')->find($order_info['buyer']);
                if ($db_ui['gzh_openid']) {
                    //发送模板消息 公众号 退款成功（给买家）
                    $data = [
                        'first' => ['value' => '您申请的退款已通过'],
                        'keyword1' => ['value' => strval($order_info['total_fee']).'元'],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => strval($order_info['id'])],
                        'keyword4' => ['value' => strval($order_info['reason'])],
                        'remark' => ['value' => '已退回微信零钱，感谢使用。'],
                    ];
                    $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'RlLrUWzjsVqcRd5DxTDhZ1mti7m97ZFxtKgsNUX_bNI', $data, 'pages/index/welcome');
                } elseif ($order_info['openid']) {
                    // 发送模板消息
                    $tData = [
                        'keyword1' => ['value' => $order_id],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => $order_info['apply_refund_money'].'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                        'keyword5' => ['value' => '已退回微信零钱'],
                    ];
                    $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], '6hSfXpoutPciTAJYli9XI05Lqzg9wH7n4GjlD2oV5E8', 'pages/index/welcome', $tData);
                }

                return error('该订单申请退款已超过3天，已经自动同意退款。');
            }

            return error('该订单申请退款已超过3天，将自动同意退款，但自动退款失败！');
        }

        $return_money = round($order_info['apply_refund_money'] - $order_info['total_postage'], 2);
        //该订单申请退货已超过3天，已经自动同意退货
        if (isset($order_info['apply_time']) && $order_info['send_time'] && $order_info['apply_time'] < time() - 86400 * 3) {
            Db::name('order')->where('id', $order_id)->update(['status' => 13, 'confirm_return_goods_time' => time()]);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 同意退货（给买家）
                $data = [
                    'first' => ['value' => '您申请退货的订单，卖家已经同意退货'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval(intval($order_info['total_number']))],
                    'keyword4' => ['value' => strval($order_info['total_money']).'元'],
                    'remark' => ['value' => '请买家在7天内发货给卖家'],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'YT1kCxUnMDp91qWS21jYqsi_XZFNUA9CQirveh9NL1A', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                // 发送模板消息
                $tData = [
                'keyword1' => ['value' => $order_id],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => $return_money.'元'],
                'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                'keyword5' => ['value' => '同意退货'],
                'keyword6' => ['value' => '请买家在7天内发货给卖家'],
            ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
            }

            return error('该订单申请退货已超过7天，已经自动同意退货。');
        }

        //拒绝退货
        if (isset($order_info['send_time']) && $order_info['send_time'] < time() && $order_info['send_time'] > time() - 86400 * 10) {
            Db::name('order')->where('id', $order_id)->update(['status' => 14, 'reject_return_goods_time' => time(), 'reject_return_goods_reason' => $reason]);
            // 订单结束 打钱给供应商并写财务明细
            financeDetail([$order_info]);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 退货失败（给买家）
                $data = [
                    'first' => ['value' => '您申请退货的订单，卖家拒绝退货'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval(intval($order_info['total_number']))],
                    'keyword4' => ['value' => strval($order_info['total_money']).'元'],
                    'remark' => ['value' => '拒绝理由：'.$reason],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'YT1kCxUnMDp91qWS21jYqsi_XZFNUA9CQirveh9NL1A', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                // 发送模板消息
                $tData = [
                'keyword1' => ['value' => $order_id],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => $return_money.'元'],
                'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                'keyword5' => ['value' => '拒绝退货'],
                'keyword6' => ['value' => $reason],
            ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
            }
        } else {
            return error('不能拒绝退款');
            // //拒绝退款
            // Db::name('order')->where('id', $order_id)->update(['status' => 8, 'reject_refund_time' => time(), 'reject_refund_reason' => $reason]);
            // // 发送模板消息
            // $tData = [
            //     'keyword1' => ['value' => $order_id],
            //     'keyword2' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
            //     'keyword3' => ['value' => $order_info['apply_refund_money'].'元'],
            //     'keyword4' => ['value' => $reason],
            //     'keyword5' => ['value' => date('Y-m-d H:i:s', time())],
            // ];
            // $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'YK4ssnWKXqs1wR_Ab-btybauc1RiBBQzT_BasMw5ZYc', 'pages/index/welcome', $tData);
        }

        return success();
    }

    // 卖家确认收货
    public function confirmReceipt()
    {
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $order_info = Db::name('order')->where(['id' => $order_id])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (4 != $order_info['status']) {
            return error('该订单不处于卖家待收货状态');
        }

        Db::name('order')->where('id', $order_id)->update(['status' => 8, 'reject_refund_time' => time()]);
        $return_money = round($order_info['apply_refund_money'] - $order_info['total_postage'], 2);
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        //退款-运费 因为第一版是单产品单地址 所以total_postage即是总运费
        $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], $order_info['total_fee'], $return_money);
        if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
            Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 15, 'seller_receive_time' => time(), 'refund_time' => time()]);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            $product = Db::name('product')->find($order_info['product'][0]['product_id']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 退货成功（给买家）
                $data = [
                    'first' => ['value' => '您的订单已经退货成功了'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => $return_money.'元'],
                    'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                    'remark' => ['value' => '卖家已收到货品，退款已退回微信零钱,感谢您的使用。'],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'zkrL0pm3VLRB6lHU4zvMl7mU1C0gLfflF5BLdmAMISE', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                // 发送模板消息
                $tData = [
                    'keyword1' => ['value' => $order_id],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => $return_money.'元'],
                    'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                    'keyword5' => ['value' => '退货成功'],
                    'keyword6' => ['value' => '卖家已收到货品，退款已退回微信零钱,感谢您的使用。'],
                ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
            }
            // 减少待结算金额
            notSettlemetnChange($order_info, false);

            return success('自动退款成功');
        }

        return error($result);
    }

    // 卖家拒绝收货 驳回 返回买家发货状态
    public function reject()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $reason = input('post.reason', '');
        if (!$reason) {
            return error('请填写理由');
        }
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $order_info = Db::name('order')->find($order_id);
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (4 != $order_info['status']) {
            return error('该订单不处于卖家待收货状态');
        }
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        //驳回 返回买家发货状态
        Db::name('order')->where('id', $order_id)->update(['status' => 2, 'send_time' => time(), 'seller_reject_receive_time' => time(), 'seller_reject_receive_reason' => $reason, 'buyer_send_number' => '', 'buyer_send_code' => '', 'buyer_send_time' => 0]);
        $product = Db::name('product')->find($order_info['product'][0]['product_id']);
        $return_money = round($order_info['apply_refund_money'] - $order_info['total_postage'], 2);
        $db_ui = Db::name('user')->find($order_info['buyer']);
        if ($db_ui['gzh_openid']) {
            //发送模板消息 公众号 驳回确认收货退货（给买家）
            $data = [
                'first' => ['value' => '您申请退货的订单，卖家已驳回，请重新发货'],
                'keyword1' => ['value' => strval($order_info['id'])],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => strval(intval($order_info['total_number']))],
                'keyword4' => ['value' => strval($order_info['total_money']).'元'],
                'remark' => ['value' => '驳回理由：'.$reason],
            ];
            $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'YT1kCxUnMDp91qWS21jYqsi_XZFNUA9CQirveh9NL1A', $data, 'pages/index/welcome');
        } elseif ($order_info['openid']) {
            // 发送模板消息
            $tData = [
                'keyword1' => ['value' => $order_id],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => $return_money.'元'],
                'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                'keyword5' => ['value' => '卖家驳回，请重新发货'],
                'keyword6' => ['value' => '驳回理由：'.$reason],
            ];
            $wx_service->sendTemplateMsg($order_info['openid'], $order_info['form_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
        }

        return success('驳回成功');
    }

    // 推送绑定
    public function bindwx()
    {
        $admin_info = session('admin_info');
        if (request()->isPost()) {
            return success();
        }
        $admin_db_info = Db::name('admin')->find($admin_info['id']);
        if ($admin_db_info['gzh_openid']) {
            $user_info = Db::name('user')->where(['gzh_openid' => $admin_db_info['gzh_openid']])->find();
        }

        return view('bindwx', ['data' => $user_info, 'admin_id' => $admin_db_info['id']]);
    }

    public function cancelOrder()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }

        $order_info = Db::name('order')->where(['id' => $order_id, 'status' => 1])->find();
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], $order_info['total_fee'], $order_info['total_fee']);
        if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
            Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 15, 'seller_receive_time' => time(), 'refund_time' => time()]);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            $product = Db::name('product')->find($order_info['product'][0]['product_id']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 退款成功（给买家）
                $data = [
                    'first' => ['value' => '您申请的退款已通过'],
                    'keyword1' => ['value' => strval($order_info['total_fee']).'元'],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval($order_info['id'])],
                    'keyword4' => ['value' => strval($order_info['reason'])],
                    'remark' => ['value' => '已退回微信零钱，感谢使用。'],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'RlLrUWzjsVqcRd5DxTDhZ1mti7m97ZFxtKgsNUX_bNI', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                // 发送模板消息
                $tData = [
                    'keyword1' => ['value' => $order_id],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => $order_info['total_fee'].'元'],
                    'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                    'keyword5' => ['value' => '已退回微信零钱'],
                ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], '6hSfXpoutPciTAJYli9XI05Lqzg9wH7n4GjlD2oV5E8', 'pages/index/welcome', $tData);
            }
            // 减少待结算金额
            notSettlemetnChange($order_info, false);

            return success('取消成功');
        }
    }

    // 导出订单
    public function export()
    {
        $admin_info = session('admin_info');
        if (6 != $admin_info['permission']) {
            return error('权限不够');
        }
        $query['admin_id'] = $admin_info['id'];
        $order = ['ct' => -1];
        vendor('PHPExcel.PHPExcel.PHPExcel');
        vendor('PHPExcel.PHPExcel.Writer.IWriter');
        vendor('PHPExcel.PHPExcel.Writer.Abstract');
        vendor('PHPExcel.PHPExcel.Writer.Excel5');
        vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        vendor('PHPExcel.PHPExcel.IOFactory');
        
        $filename = '订单导出'.date('Y-m-d H-i-s').'.xlsx';
        $objPHPExcel = new \PHPExcel();
        $objSheet = $objPHPExcel->getActiveSheet();
        $objSheet->setTitle('订单');
        $list = Db::name('order')->where($query)->order($order)->select();
        $arr = [];
        $arr[] = ['订单号', '客户网名', '收货人', '电话', '国家', '州省', '区市', '区县', '地址', '邮编', 'Email', 'QQ', '客服备注', '客户备注', '应收邮资', '编号', '品名', '规格', '条码', '附加码', '单位', '数量', '单价', '合计', '货品备注', '发票抬头', '业务员', '订单来源', '优惠金额'];
        foreach ($list as $data) {
            $row = [];
            $user_info = Db::name('user')->find($data['buyer']);
            // 1.0版本只有单地址 单商品（可以多规格）
            $address_info = Db::name('address')->find($data['address'][0]['address_id']);
            $product_info = Db::name('product')->find($data['product'][0]['product_id']);
            $row[] = $data['id'];
            $row[] = strval($user_info['name']);
            $row[] = strval($address_info['consignee']);
            $row[] = strval($address_info['phone']);
            $row[] = '中国';
            $row[] = strval($address_info['province']);
            $row[] = strval($address_info['city']);
            $row[] = strval($address_info['county']);
            $row[] = strval($address_info['address']);
            $row[] = '';
            $row[] = '';
            $row[] = '';
            $row[] = ''; //todo 客服备注
            $row[] = strval($data['remark']);
            $row[] = round($data['total_postage'], 2);
            $info_data = [];
            foreach ($data['product'] as $key => $value) {
                foreach ($product_info['specifications'] as $kk => $vv) {
                    if ($vv['title'] == $value['specifications']) {
                        $info_data['code'][] = strval($vv['code']);
                        $info_data['specifications'][] = $vv['title'];
                        $info_data['number'][] = intval($value['number']);
                        $info_data['real_supply'][] = round($value['real_supply'], 2);
                    }
                }
            }
            $row[] = implode("/", $info_data['code']);
            $row[] = strval($product_info['name']);
            $row[] = implode("/", $info_data['specifications']);
            $row[] = '';
            $row[] = '';
            $row[] = '';
            $row[] = implode("/", $info_data['number']);
            $row[] = implode("/", $info_data['real_supply']);
            $row[] = round($data['total_real_supply'], 2);
            $row[] = '';
            $row[] = '';
            $row[] = '';
            $row[] = '羽毛球VIP';
            $row[] = '';
            
            $arr[] = $row;
        }
        $objSheet->fromArray($arr);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

        $objWriter->save('php://output');
    }
}
